package com.neegix.organization.psn.application.cqrs.command;

import com.neegix.application.command.ICommand;
import com.neegix.organization.psn.domain.entity.PsnEntity;
import com.neegix.organization.psn.domain.entity.PsnWorkInfoValue;
import com.neegix.organization.psn.infrastructure.repository.convert.PsnConverter;
import com.neegix.organization.psn.infrastructure.repository.convert.PsnWorkInfoConverter;
import com.neegix.organization.psn.infrastructure.repository.mapper.PsnMapper;
import com.neegix.organization.psn.infrastructure.repository.mapper.customized.PsnWorkInfoCustomizedMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Collections;
import java.util.List;

/**
  * This file is auto-generated by nebula-framework-generator.
  * The auto-generation plugin was developed using IntelliJ IDEA Community Edition.
  * Thanks to JetBrains for their outstanding contributions to the developer community.
  * <p>
  * The code generated by this tool is owned by the user of the tool.
  * The tool itself is copyrighted by <a href="https://www.neegix.com">https://www.neegix.com</a>.
  *
  * @author <a href="https://www.neegix.com">https://www.neegix.com</a>
  * @version 1.0.0
  * @since 2024-12-11 15:13:32
  */

public class NewPsnCommand implements ICommand<Void> {
    private final PsnEntity psnEntity;

    public NewPsnCommand(PsnEntity psnEntity) {
        this.psnEntity = psnEntity;
    }

    @Override
    public Void execute(ApplicationContext context) {
        //启用事务
        TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class);
        transactionTemplate.execute(status -> {
            PsnMapper psnMapper = context.getBean(PsnMapper.class);
            psnMapper.insert(PsnConverter.INSTANCE.covertDO(psnEntity));

            PsnWorkInfoCustomizedMapper psnWorkInfoCustomizedMapper = context.getBean(PsnWorkInfoCustomizedMapper.class);

            psnWorkInfoCustomizedMapper.batchDeleteByPkPsn(Collections.singletonList(psnEntity.getId()));

            List<PsnWorkInfoValue> psnWorkInfoValues = psnEntity.getPsnWorkInfos();
            psnWorkInfoValues.forEach(item-> item.setPkPsn(psnEntity.getId()));

            psnWorkInfoCustomizedMapper.batchInsertPsnWorkInfo(PsnWorkInfoConverter.INSTANCE.covertDO(psnWorkInfoValues));
            return null;
        });

        return null;
    }
}
